﻿//var savedRange, isInFocus;
//function saveSelection() {
//    if (window.getSelection)//non IE Browsers
//    {
//        savedRange = window.getSelection().getRangeAt(0);
//    }
//    else if (document.selection)//IE
//    {
//        savedRange = document.selection.createRange();
//    }
//}

//function restoreSelection() {
//    isInFocus = true;
//    document.getElementById("area").focus();
//    if (savedRange != null) {
//        if (window.getSelection)//non IE and there is already a selection
//        {
//            var s = window.getSelection();
//            if (s.rangeCount > 0)
//                s.removeAllRanges();
//            s.addRange(savedRange);
//        }
//        else
//            if (document.createRange)//non IE and no selection
//            {
//                window.getSelection().addRange(savedRange);
//            }
//            else
//                if (document.selection)//IE
//                {
//                    savedRange.select();
//                }
//    }
//}


var browserName = getBrowserName();

//try to do java before postback
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);

function InitializeRequest(sender, args) {
    $('input[id$="_HiddenTextArea"]').val(nicEditors.findEditor('FinishedText').getContent());
}


var nic;
bkLib.onDomLoaded(function () {
    try {
        startNicEditor();
        //setting the content from the hidden text area to nicEdit
        nicEditors.findEditor('FinishedText').setContent($('input[id$="_HiddenTextArea"]').val());
    }
    catch (ex) { }

});


function getBrowserName() {
    var browserName1 = navigator.appName;
    if (browserName1 == "Microsoft Internet Explorer") return "Microsoft Internet Explorer";
    else if (browserName1 == "Opera") return "Opera";
    else if (browserName1 == "Netscape") {
        var stringContainingName = navigator.userAgent;
        if (stringContainingName.match(/Safari/gi) == "Safari") {
            if (stringContainingName.match(/Chrome/gi) == "Chrome") return "Chrome";
            else return "Safari";
        }
        else if (stringContainingName.match(/Chrome/gi) == "Chrome") return "Chrome";
        else if (stringContainingName.match(/Firefox/gi) == "Firefox") return "Firefox";
        else return "unknown";
    }
    else return "unknown";
}


//    <!-- start-stop NicEdit, get browser -->

function startNicEditor() {
    nic = new nicEditor({ fullPanel: false, position: { my: "right top", at: "right bottom" }, iconsPath: 'img/nicEditorIcons.gif', buttonList: ['fontSize', 'fontFamily', 'forecolor', 'bold', 'italic', 'underline', 'strikethrough', 'left', 'center', 'right'], externalCSS: 'Styles/Site.css' })
			.panelInstance('FinishedText', { hasPanel: true });
    nic.addEvent('blur',function () {
				    //setting the content from the hidden text area to nicEdit
				    currentEditorText = nicEditors.findEditor('FinishedText').getContent();
				    if (currentEditorText != $('input[id$="_HiddenTextArea"]').val()) {
				        $('input[id$="_HiddenTextArea"]').val(currentEditorText);
				    }
				});
}

function updateGeneratorAfterNicEdited() {

    alert("nicedit text: \n" + "|" + nicEditors.findEditor('FinishedText').getContent() + "|");
    var nicTextTags = nicEditors.findEditor('FinishedText').getContent();

    alert("we've got " + browserName);

    switch (browserName) {
        case "Chrome":
            {
                nicTextTags = nicTextTags.replace(/<br>/gi, "");
                //nicTextTags = nicTextTags.replace(/&nbsp;/gi, "");
                nicTextTags = nicTextTags.replace(/<div/gi, "998877<div");
            }
            break;
        case "Microsoft Internet Explorer":
            {
                nicTextTags = nicTextTags.replace(/&nbsp;/gi, " ");
                //nicTextTags = nicTextTags.replace(/&nbsp;/gi, "");
                nicTextTags = nicTextTags.replace(/<p/gi, "998877<p");
                nicTextTags = nicTextTags.replace(/998877/, "");
            }
            break;
        case "Firefox":
            {
                nicTextTags = nicTextTags.replace(/<br/gi, "998877<br");
                nicTextTags = nicTextTags.replace(/&nbsp;/gi, " ");
                nicTextTags = nicTextTags.replace(/998877<br>([^998877<br>]*)$/, '$1'); //remove the last <br>, it's redundant
            }
            break;
        case "Opera":
            {
                nicTextTags = nicTextTags.replace(/&nbsp;/gi, " ");
                //nicTextTags = nicTextTags.replace(/<br>/gi, "");
                nicTextTags = nicTextTags.replace(/<p/gi, "998877<p");
                nicTextTags = nicTextTags.replace(/998877/, "");
            }
            break;
        case "Safari":
            {
                //nicTextTags = nicTextTags.replace(/&nbsp;/gi, "");
                nicTextTags = nicTextTags.replace(/<div/gi, "998877<div");
                //nicTextTags = nicTextTags.replace(/998877/, "");
            }
            break;
        default:
            {
                nicTextTags = nicTextTags.replace(/<p><br>/gi, "<p>");
                nicTextTags = nicTextTags.replace(/<div/gi, "998877<div"); // 998877 is place holder for future \n
                nicTextTags = nicTextTags.replace(/<p/gi, "998877<p");
                nicTextTags = nicTextTags.replace(/<br/gi, "998877<br");
            }
    }


    alert(nicTextTags);


    $(function () {
        var zxc2 = $("<span>" + nicTextTags + "</span>").text(); //remove html tags
        zxc2 = zxc2.replace(/998877/gi, "\n");
        alert(my_function().toString);
    });



}

function removeHtmlTags(text) {
    var zxc2 = $("<span>" + text + "</span>").text(); //remove html tags
    zxc2 = zxc2.replace(/998877/gi, "\n");
    return zxc2;
}



//<!-- AUTOCOMPLETE function -->


my_function = null;

var tempString = "";
currentEditorText = "";
var tempVar;
var modelTextOriginal = '';
var savedNicCursorPosition = nicEditors.findEditor('FinishedText');


try {
    modelTextOriginal = $("span#MainContent_DataList1_TextModelLabel_0").html(); // document.getElementById("MainContent_DataList1_TextModelLabel_0").innerHTML;
    //alert(modelTextOriginal);
} catch (ex) {
    //alert("NO Model text available"); 
}


var rangySavedSel = null;
var rangySavedSelActiveElement = null;

function rangySaveSelection() {
    // Remove markers for previously saved selection
    if (rangySavedSel) {
        rangy.removeMarkers(rangySavedSel);
    }
    rangySavedSel = rangy.saveSelection();
    rangySavedSelActiveElement = document.activeElement;
}

function rangyRestoreSelection() {
    if (rangySavedSel) {
        rangy.restoreSelection(rangySavedSel, true);
        rangySavedSel = null;
        window.setTimeout(function () {
            if (rangySavedSelActiveElement && typeof rangySavedSelActiveElement.focus != "undefined") {
                rangySavedSelActiveElement.focus();
            }
        }, 1);
    }
}

bkLib.onDomLoaded(function () {
    $(".nicEdit-main").autocomplete({
        source: function (request, response) {
            $.getJSON("AutoComplete.ashx", {
                term: extractLastWord(request.term)[1],
                gender: function () {
                    return $('input[id$="_GenreHiddenTextArea"]').val();
                }
            }, response);
        },
        position: { my: "right top", at: "right bottom" },
        search: function () {
            // custom minLength  
            var term = extractLastWord(sanatiseText(nicEditors.findEditor('FinishedText').getContent()))[1];
            if (term.length < 1) {
                return false;
            }
            savedNicCursorPosition = window.getSelection(); //nicEditors.findEditor('FinishedText').getSel();
            rangySaveSelection();
        },
        focus: function () {
            // prevent value inserted on focus 
            return false;
        },
        select: function (event, ui) {

            var terms = nicEditors.findEditor('FinishedText').getContent();
            var elementsInTerms = extractLastWord(terms);

            var beginningElement = elementsInTerms[0];
            var foundWord = elementsInTerms[1];
            var endingElement = elementsInTerms[2];
            var foundWordIndex = elementsInTerms[3];

            var abreviationText = ui.item.TextAbreviere;
            abreviationText = getTextFormat(abreviationText, ui);
            var cursorPositionDiv = "<div class='nicCursorPositionDiv' contentEditable='true' ></div>";

            terms = beginningElement + abreviationText + endingElement;
            var curNicEdit = nicEditors.findEditor('FinishedText');

            curNicEdit.setContent(terms);
            rangyRestoreSelection();

            return false;
        }
    })
	.data("autocomplete")._renderItem = function (ul, item) {
		return $("<li></li>")
			.data("item.autocomplete", item)
			.append("<a>" + item.Abreviere + " : " + item.TextAbreviere + " - " + item.Specialitate + "</a>")
			.appendTo(ul);
	};

});

function getSelectedGender() {
    if ($('#<%= RadioButtonList.ClientID %> input:checked').val()) {
        
    }
}

function getTextFormat(tempString4, ui) {
        tempString4 = isTextBold(ui.item.Bold, true) + isTextItalic(ui.item.Italic, true) + getTextSize(ui.item.MarimeText, true)
					+ tempString4
					+ isTextBold(ui.item.Bold, false) + isTextItalic(ui.item.Italic, false) + getTextSize(ui.item.MarimeText, false)
                    + '&nbsp;';

        return tempString4;
    }

    function sanatiseText(input) {
        return input.replace(/&nbsp;/gi, ' ');
    }

    function updateModel(lastWord, terms) {
        var modelTextResult = "";
        var modelTextRed = "<font color='red'>";
        var generatorTextTemp = terms.split(" ");
        var generatorTextTemp2 = generatorTextTemp;
        var matchesInEditor = "";

        var s1, s2;
        do {
            lastWord = $("<div>" + (generatorTextTemp.pop()).toString() + "</div>").text();
            var lastWordRepetitions = 0;

            if (lastWord.length > 3) {

                matchesInEditor = terms.match(/lastWord/gim);
                if (matchesInEditor) {
                    lastWordRepetitions = matchesInEditor.length;
                } else {
                    lastWordRepetitions = 0;
                }
                //                                for (var i = 0; i < terms.length - 1; i++) {
                //                                    
                //                                    s1 = generatorTextTemp2[i].toLowerCase();
                //                                    try {
                //                                        //get rid of all the signs(except a few) and keep only the letters in the word
                //                                        s1 = generatorTextTemp2[i].match(/[A-z]/g).toString();
                //                                    } catch (ex) {
                //                                    }

                //                                    if (s1.toLowerCase() == lastWord.toLowerCase().match(/[A-z]/g).toString()) {
                //                                        lastWordRepetitions++;
                //                                    }
                //                                }

                if (lastWordRepetitions > 0) {

                    var modelText = modelTextOriginal;
                    var modelTextTemp = modelText.split(" ");

                    for (var i = 0; i < modelTextTemp.length; i++) {
                        s2 = modelTextTemp[i].toLowerCase();
                        try {
                            //get rid of all the signs(except a few) and keep only the letters in the word
                            s2 = modelTextTemp[i].match(/[A-z]/g).toString();
                        } catch (ex) {
                        }

                        if (s2.toLowerCase() == lastWord.toLowerCase().match(/[A-z]/g).toString()) {
                            lastWordRepetitions--;
                            if (lastWordRepetitions == 0) {
                                modelTextTemp.splice(i + 1, 0, "</font><div id='imHere' style='position: absolute; bottom: 100px'></div>");
                                modelTextResult = modelTextRed + modelTextTemp.join(" ");

                                document.getElementById("MainContent_DataList1_TextModelLabel_0").innerHTML = modelTextResult;
                                document.getElementById('imHere').scrollIntoView(true);

                                break;
                            }
                        }
                    }
                }
            }

        } while (lastWord.length < 4);

    }
    
    function extractLastWord(term) {
        //remove html tags
        var elementsInTerms = new Array();

        elementsInTerms[0] = ""; //begining element
        elementsInTerms[1] = ""; //found word
        elementsInTerms[2] = ""; //ending element
        elementsInTerms[3] = -1; //location for first letter of the found word


        if (term == undefined || term == "") {
            return elementsInTerms;
        }

        if (term == "\uFEFF") {
            return elementsInTerms;
        }
        
//regex returns true if string contains only ascii chars        
//        var regexPattern = /^[\x00-\x7F]*$/;
//        if (!regexPattern.test(term)) {
//            return elementsInTerms;
//        }

        elementsInTerms[1] = term; //found word
        
        var initialText = term;
        var endingElement = "";
        var foundWord = "";
        var beginningElement = "";
        var isWordFound = false;
        var foundWordStartIndex = -1;

        var whiteSpaceRegex = /\s|\n|\r|\t/gim;

        var i = initialText.length - 1;

        while (i >= 0) {
            while (!isWordFound) {
                if (isThisWhiteSpace(initialText.charAt(i)) && !isThisSpecialCharacter(initialText.charAt(i))) {
                    while (i >= 0) {
                        beginningElement += initialText.charAt(i);
                        i--;
                    }
                    isWordFound = true; //not found here, but needs to break from while loop
                }
                else {
                    while (!isWordFound) {
                        while (initialText.charAt(i) != ">" && initialText.charAt(i) != "<" && !isThisWhiteSpace(initialText.charAt(i))
                                                                    && !isThisSpecialCharacter(initialText.charAt(i)) && i >= 0) {
                            foundWord += initialText.charAt(i);
                            isWordFound = true;
                            foundWordStartIndex = i;
                            i--;
                        }
                        if (initialText.charAt(i) == ">") {
                            while (initialText.charAt(i) != "<" && i >= 0) {
                                if (isWordFound) {
                                    beginningElement += initialText.charAt(i);
                                } else {
                                    endingElement += initialText.charAt(i);
                                }
                                i--;
                            }
                        }
                        if (initialText.charAt(i) == "<") {
                            if (isWordFound) {
                                beginningElement += initialText.charAt(i);
                            } else {
                                endingElement += initialText.charAt(i);
                            }
                            i--;
                        }
                        if (isThisSpecialCharacter(initialText.charAt(i))) {
                            if (isWordFound) {
                                beginningElement += initialText.charAt(i);
                            } else {
                                endingElement += initialText.charAt(i);
                            }
                            i--;
                        }
                        if (isThisWhiteSpace(initialText.charAt(i)) && !isThisSpecialCharacter(initialText.charAt(i))) {
                            isWordFound = true; //not found here, but needs to break from while loop
                        }
                    } if (isWordFound) {
                        while (i >= 0) {
                            beginningElement += initialText.charAt(i);
                            i--;
                        }
                    }
                }

            }
        }

        function isThisWhiteSpace(charToVerify) {
            if (whiteSpaceRegex.test(charToVerify)) {
                return true;
            } else {
                return false;
            }
        }

        function isThisSpecialCharacter(charToVerify) {
            if (escape(charToVerify) == "%uFEFF") {
                return true;
            } else {
                return false;
            }
        }

        elementsInTerms[0] = beginningElement.split('').reverse().join('');
        elementsInTerms[1] = foundWord.split('').reverse().join('');
        elementsInTerms[2] = endingElement.split('').reverse().join('');
        elementsInTerms[3] = foundWordStartIndex;

        return elementsInTerms;
    }

    function removeHtmlTags(text) {
        var x = $("<span>" + term + "</span>").text();
        x = splitOnSpaceAndDot(x).pop();
    }


    function split(val) {
        return val.split(/ \s*|\r\n|\r|\n/);
        //return val.split(" ");
    }

    function splitOnSpaceAndDot(val) {
        return val.split(/[\s.]+/);
    }

    function splitOnSpace(val) {
        return val.split(" ");
    }

    function splitOnEnter(val) {
        return val.split(/\r\n|\r|\n/);
    }

    function splitOnDot(val) {
        return val.split(".");
    }

function isTextBold(b, tag) {
    if ((b != "True") && (b != "False")) return "";

    else if (b == "True") {
        if (tag == true) return "<b>";

        else return "</b>";
    }
    else if (b == "False") return "";
    return "";
}


function isTextItalic(b, tag) {
    if ((b != "True") && (b != "False")) return "";

    else if (b == "True") {
        if (tag == true) return "<i>";

        else return "</i>";
    }
    else if (b == "False") return "";
    return "";
}


function getTextSize(b, tag) {
    if ((b == "") || (b == "NULL") || (b == "null") || (b == "Null") || (b == null) || (b == "False") || (b == "false") || (b == false) || (b == "0") || (b == "undefined") || (b == "UNDEFINED") || (b == "Undefined")) return "";

    else if (tag == true) return "<font size='" + b + "'>";
    else if (tag == false) return "</font>";
    return "";
}

